package com.seed.launcher.listener;

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;

import androidx.annotation.Keep;
import androidx.annotation.NonNull;

/**
 * 亮度监听
 * 亮度值:1~255
 *
 * @author xct
 * create on: 2022/8/30 10:38
 */
@Keep
public class BrightnessListener extends ContentObserver implements Registerable{

    private static final String TAG = "BrightnessListener";
    private final Context mContext;
    private final OnValueChangedCallback mCallback;

    public BrightnessListener(Context context, @NonNull OnValueChangedCallback callback) {
        super(new Handler());
        mContext = context;
        mCallback = callback;
    }


    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        int systemBrightness = getSystemBrightness(mContext.getContentResolver());
        Log.i(TAG, "on Brightness Change: "+systemBrightness);
        float ratio = 1f*systemBrightness / 255f;
        ratio = Math.max(0, Math.min(ratio, 1f));
        mCallback.onChanged(ratio);
    }

    public static int getSystemBrightness(ContentResolver cr) {
        int systemBrightness = 0;
        try {
            systemBrightness = Settings.System.getInt(cr, Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return systemBrightness;
    }

    @Override
    public void register() {
        Uri brightnessUri = Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
        mContext.getContentResolver().registerContentObserver(brightnessUri, true, this);
        //主动获取
        onChange(true);
    }

    @Keep
    @Override
    public void unregister() {
        mContext.getContentResolver().unregisterContentObserver(this);
    }

}
